package com.qf.openapi.web.master.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.openapi.web.master.dao.ApiMappingDao;
import com.qf.openapi.web.master.entity.ApiMapping;
import com.qf.openapi.web.master.service.ApiMappingService;
import com.qf.openapi.web.master.vo.ResultVo;
import com.qf.openapi.web.master.vo.TableVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public class ApiMappingServiceImpl implements ApiMappingService {
    @Autowired
    private ApiMappingDao apiMappingDao;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public TableVo<ApiMapping> getApiMappingsByContdition(Integer page, Integer limit, ApiMapping apiMapping) {
        PageHelper.startPage(page, limit);
        List<ApiMapping> apiMappings = apiMappingDao.getApiMappingsByContdition(apiMapping);
        PageInfo<ApiMapping> pageInfo = new PageInfo<>(apiMappings);
        TableVo<ApiMapping> tableVo = null;
        if (apiMappings != null) {
            tableVo = new TableVo<>(0, "OK", (int) pageInfo.getTotal(), apiMappings);
        } else {
            tableVo = new TableVo<>(-1, "ERROR", (int) pageInfo.getTotal(), null);
        }
        return tableVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo delApiMappingByIds(Integer[] ids) {
        Integer flag = apiMappingDao.delApiMappingByIds(ids);
        if (flag > 0) {
            return new ResultVo(1, "删除成功");
        }
        return new ResultVo(-1, "删除失败");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo addApiMapping(ApiMapping apiMapping) {
        Integer flag = apiMappingDao.addApiMapping(apiMapping);
        if (flag > 0) {
            return new ResultVo(1, "添加成功");
        }
        return new ResultVo(-1, "添加失败");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo updateApiMapping(ApiMapping apiMapping) {
        Integer flag = apiMappingDao.updateApiMapping(apiMapping);
        if (flag > 0) {
            return new ResultVo(1, "修改成功");
        }
        return new ResultVo(-1, "修改失败");
    }
}
